<?php

class user_pointModel extends Model {
	const INC = 1;
	const DEC = 2;
	private $error;

	const TITLE_DYNAMIC = '内容推荐奖励积分';
	const TITLE_DYNAMIC_SHARE = '内容分享奖励积分';
	const TITLE_GOODS_SHARE = '商品分享奖励积分';

	public function buildRebateTitle($pointType) {
		if ($pointType == user_rebateModel::POINT_TYPE_DYNAMIC) {
			return self::TITLE_DYNAMIC;
		} elseif ($pointType == user_rebateModel::POINT_TYPE_SHARE_DYNAMIC) {
			return self::TITLE_DYNAMIC_SHARE;
		} else {
			return self::TITLE_GOODS_SHARE;
		}
	}

	/**
	 * 增加用户积分方法
	 * 若返回false 根据getError方法获取失败信息
	 */
	public function inc($uid, $point, $title) {
		// // $this->startTrans();
		// // //增加用户总积分
		// // if($this->execute("update wf_user set points=points+{$point} where uid={$uid}")&&
		// // $this->insert([
		// //     'uid' => $uid,
		// //     'type' => self::INC,
		// //     'title' => $title,
		// //     'point' => $point,
		// //     'year' => date('Y'),
		// //     'month' => date('m'),
		// //     'add_time' => time()
		// // ])) {
		// //     $this->commit();
		// //     $this->model('user')->deleteCacheById($uid);
		// //     return true;
		// // }
		// // $this->error = '增加积分失败,请稍后再试';
		// // $this->rollback();
		// return false;
	}

	/**
	 * 减少用户积分方法
	 * 若返回false 根据getError方法获取失败信息
	 */
	public function dec($uid, $point, $title) {
		// $userInfo = $this->query("select points from wf_user where uid=?", $uid)->fetchRow();
		// if ($userInfo['points'] < $point) {
		// 	$this->error = '用户积分数低于扣减积分值';
		// 	return false;
		// }
		// $this->startTrans();
		// //增加用户总积分
		// if ($this->execute("update wf_user set points=points-{$point} where uid={$uid} AND points={$userInfo['points']}") &&
		// 	$this->insert([
		// 		'uid' => $uid,
		// 		'type' => self::DEC,
		// 		'title' => $title,
		// 		'point' => $point,
		// 		'year' => date('Y'),
		// 		'month' => date('m'),
		// 		'add_time' => time(),
		// 	])) {
		// 	$this->commit();
		// 	$this->model('user')->deleteCacheById($uid);
		// 	return true;
		// }
		// $this->error = '扣减积分失败,请稍后再试';
		// $this->rollback();
		// return false;
	}

	public function getList($where, $value, $page = 1, $pageSize = 15) {
		return [
			'page' => $page,
			'pageSize' => $pageSize,
			'list' => $this->formateData($this->fields('type, point,title,add_time')->order('id desc')
					->limit(($page - 1) * $pageSize, $pageSize)
					->getAll($where, $value)),
		];
	}

	public function formateData($data) {
		if (!$data) {
			return array();
		}
		foreach ($data as $key => $value) {
			if (is_array($value)) {
				$data[$key] = $this->formateData($value);
			} else {
				switch ($key) {
				case 'uid':
				case 'id':
				case 'type':
				case 'point':
					$data[$key] = (int) $value;
					break;
				case 'add_time':
					$data['addTime'] = date('Y-m-d H:i', $data[$key]);
					unset($data[$key]);
					break;
				default:
					$data[$key] = (string) $value;
				}
			}
		}
		return $data;
	}

	public function getError() {
		return $this->error;
	}
}